import { fileURLToPath, URL } from 'node:url'
import process from 'node:process'

import { defineConfig, loadEnv } from 'vite'
// import legacy from '@vitejs/plugin-legacy'
import vue2 from '@vitejs/plugin-vue2'

import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from '@vant/auto-import-resolver'

import px2vw from 'postcss-px-to-viewport-8-plugin'
import UnoCSS from 'unocss/vite'

// https://vitejs.dev/config/
export default defineConfig((mode) => {
  const env = loadEnv(mode, process.cwd(), '')

  return {
    base: env.VITE_PUBLIC_PATH,

    plugins: [
      vue2(),
      AutoImport({
        imports: ['vue'],
        vueTemplate: true,
        resolvers: [VantResolver()]
      }),
      Components({
        version: 2.7,
        dirs: ['src/components'],
        resolvers: [VantResolver()]
      }),
      // legacy({
      //   targets: ['ie >= 11'],
      //   additionalLegacyPolyfills: ['regenerator-runtime/runtime']
      // }),
      UnoCSS()
    ],
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: {
            // vant theme override
          },
          javascriptEnabled: true
        }
      },
      postcss: {
        plugins: [
          px2vw({
            unitToConvert: 'px',
            viewportWidth: 375,
            unitPrecision: 3,
            propList: ['*'],
            viewportUnit: 'vw',
            fontViewportUnit: 'vw',
            selectorBlackList: ['.ignore'],
            minPixelValue: 1,
            mediaQuery: true,
            replace: true,
            exclude: [],
            landscape: false,
            landscapeUnit: 'vw',
            landscapeWidth: 568
          })
        ]
      }
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      proxy: {
        '/proxy': {
          target: 'https://t-sentiment.ybsjyyn.com',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/proxy/, '')
        }
      }
    }
  }
})
